package com.yssoft.controller.app.system;

import com.google.common.annotations.VisibleForTesting;
import com.yssoft.entity.core.*;
import com.yssoft.mapper.core.TAccountsMapper;
import com.yssoft.service.core.AccountsService;
import com.yssoft.service.core.DepartmentService;
import com.yssoft.service.core.EnterpriseService;
import com.yssoft.service.core.PersonService;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.ObjectConversion;
import com.yssoft.utils.UploadFile;
import com.yssoft.utils.verificationCode.CCPRestSDK;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 王永宁
 * @说明 APP个人信息
 * @time 2018/4/29 上午 09:06
 */
@CrossOrigin//解决跨域session问题
@Controller
@RequestMapping("/app/appPersonal")
public class AppPersonalController {
	 @Resource
	 private TAccountsMapper accountsMapper;
	 @Resource
	 private AccountsService accountsService;
	 
	 @Resource
	 private PersonService personService;
	 
	 @Resource
	 private DepartmentService departmentService;
	 
	 @Resource
	 private EnterpriseService enterpriseService;
	 
	    /**
	      * @author 王永宁
	      * @说明 APP个人资料
	     * @return
	     */
	    @RequestMapping(value = "information", method = RequestMethod.POST)
	    @ResponseBody
	    public String information(HttpServletRequest request) {
	    	String res;
			try {
				 Integer pId = AppUserHelper.getCurrentUserId(request);
				TAccounts acc = accountsService.queryAccountByPersonId(pId);
				TPersonnel person;
				TDepartment dept;
				try {
					person = personService.queryPersonById(pId.toString());
					try {
						dept = departmentService.queryTDepartmentById(person.gettDId());
						List<String> rolesList = accountsService.queryRolesByAccId(acc.getId());
						res = "{\"result\": {\"code\": \"1\",\"data\": {\"name\": \""+person.getName()+"\",\"loginName\": \""+acc.getLoginName()+"\",\"sex\": \""+person.getSex()+"\",\"phone\": \""+person.getPhone()+"\",\"deptName\": \""+dept.getName()+"\",\"roles\": \""+rolesList+"\"},\"msg\":\"success\"}}";
					
					} catch (Exception e) {
						res = "{\"result\": {\"code\": \"0\",\"data\": {},\"msg\":\"1部门ID不正确\"}}";
					}
					} catch (Exception e) {
					res = "{\"result\": {\"code\": \"0\",\"data\": {},\"msg\":\"2人员ID不正确\"}}";
				}
				} catch (Exception e) {
					e.printStackTrace();
					res = "{\"result\": {\"code\": \"0\",\"data\": {},\"msg\":\"fail\"}}";
				}
	    	return res;
	    }
	 
	    
	    /**
	      * @author 王永宁
	      * @说明 APP企业信息
	     * @return
	     */
	    @RequestMapping("enterprise")
	    @ResponseBody
	    public Object enterprise(Integer id,HttpServletRequest request) {
				try {
					TEnterprise enterprise = enterpriseService.queryEnterpriseById(id);
					Map<String, Object> map = ObjectConversion.getObjectToMap(enterprise);//将实体转换成map
					return AppUtil.returnMapJson("1", "查询成功", map);
				} catch (Exception e) {
					return AppUtil.returnMapJson("0", "查询失败", null);
				}
	    }
	    /**
	      * @author 王永宁
	      * @说明 APP获取企业图片信息
	     * @return
	     */
	    @RequestMapping("licence")
	    @ResponseBody
	    public Object licence(Integer id,HttpServletRequest request) {
				try {
					TEnterpriseLicence licence = enterpriseService.queryLicenceByEId(id);
					Map<String, Object> map = ObjectConversion.getObjectToMap(licence);//将实体转换成map
					return AppUtil.returnMapJson("1", "查询成功", map);
				} catch (Exception e) {
					return AppUtil.returnMapJson("0", "查询失败", null);
				}
	    }
	    /**
	     * @author 王永宁
	     * @说明 APP保存企业
	     * @return
	     */
	    @RequestMapping(value="saveEnterprise",method = RequestMethod.POST)
	    @ResponseBody
	    public Object saveEnterprise(TEnterprise enterprise,String LvLo, String licenceImg, String licenceTimg,HttpServletRequest request) {
	    	MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest)request;
	    	MultipartFile logo = mrequest.getFile("logo");
	    	MultipartFile zhizhao = mrequest.getFile("zhizhao");
	    	MultipartFile idcardFile = mrequest.getFile("idcardFile");
	    	if(idcardFile!=null){
	    		Map<String, Object> idcard = UploadFile.compressUploadedFile(idcardFile);
	    		enterprise.setIdcardImg(idcard.get("fileName").toString());
	    		enterprise.setIdcardTimg(idcard.get("thumbnails").toString());
	    	}else{
	    		enterprise.setIdcardImg(enterprise.getIdcardImg().substring(enterprise.getIdcardImg().indexOf("/files")));
	    		enterprise.setIdcardTimg(enterprise.getIdcardTimg().substring(enterprise.getIdcardTimg().indexOf("/files")));
	    	}
	    	if(logo!=null){
		    	Map<String, Object> logos = UploadFile.compressUploadedFile(logo);
		    	enterprise.setLogoImg(logos.get("fileName").toString());
		    	enterprise.setLogoTimg(logos.get("thumbnails").toString());
	    	}else if(LvLo.contains("1")){
	    		enterprise.setLogoImg(enterprise.getLogoImg().substring(enterprise.getLogoImg().indexOf("/files")));
	    		enterprise.setLogoTimg(enterprise.getLogoTimg().substring(enterprise.getLogoTimg().indexOf("/files")));
	    	}else{
	    		enterprise.setLogoImg("");
		    	enterprise.setLogoTimg("");
	    	}
	    	if(zhizhao!=null){
	    		Map<String, Object> zhizhaos = UploadFile.compressUploadedFile(zhizhao);
	    		licenceImg=zhizhaos.get("fileName").toString();
	    		licenceTimg=zhizhaos.get("thumbnails").toString();
	    	}else{
	    		licenceImg=licenceImg.substring(licenceImg.indexOf("/files"));
	    		licenceTimg=licenceTimg.substring(licenceTimg.indexOf("/files"));
	    	}
	    	String msg ="" ;
	    	try {
				 msg = enterpriseService.updeteEnterprise(enterprise,licenceImg,licenceTimg);
				return AppUtil.returnMapJson("1", msg, null);
			} catch (Exception e) {
				return AppUtil.returnMapJson("0", msg, null);
			}
	    }
	    /**
	     * @author 王永宁
	     * @说明 APP校验原密码
	     * @return
	     */
	    @RequestMapping("checkPassword")
	    @ResponseBody
	    public Object checkPassword(String password,HttpServletRequest request) {
	    	Integer pId = AppUserHelper.getCurrentUserId(request);
	    	TAccounts acc = accountsService.queryAccountByPersonId(pId);
	    	//用户传输过来的密码
            String newSashPassword = new SimpleHash("MD5", password == null ? "" : password, acc.getSalt(), 2).toString();
            //数据库中查询的密码
            String sashPassword = acc.getPassword();
            if (newSashPassword.equals(sashPassword)) {
            	return AppUtil.returnMapJson("1", "登陆密码正确!", null);
            } else {
                return AppUtil.returnMapJson("0", "登陆密码错误!", null);
            }
	    }
	    /**
	     * @author 王永宁
	     * @说明 APP修改密码
	     * @return
	     */
	    @RequestMapping("updatePassword")
	    @ResponseBody
	    public Object updatePassword(String newPassword,String oldPassword,HttpServletRequest request) {
	    	Integer pId = AppUserHelper.getCurrentUserId(request);
	    	TAccounts acc = accountsService.queryAccountByPersonId(pId);
	    	//用户传输过来的密码
            String newSashPassword = new SimpleHash("MD5", oldPassword == null ? "" : oldPassword, acc.getSalt(), 2).toString();
            //数据库中查询的密码
            String sashPassword = acc.getPassword();
            if (newSashPassword.equals(sashPassword)) {
            	 String salt= System.currentTimeMillis()+acc.gettPId()+"";
                 acc.setSalt(salt);//随机加密盐
                 String password = new SimpleHash("MD5", newPassword, salt, 2).toString();
                 acc.setPassword(password);
                 accountsService.updateAccountById(acc);
            	return AppUtil.returnMapJson("1", "修改成功!", null);
            } else {
                return AppUtil.returnMapJson("0", "原密码错误!", null);
            }
	    	
	    }
	    
	    /**
	     * @author 王永宁
	     * @说明 APP更换手机号
	     * @return
	     */
	    @RequestMapping("changePhone")
	    @ResponseBody
	    public Object changePhone(String phoneNumber) {
	    	try {
				TPersonnel person = personService.queryPersonByPhone(phoneNumber);
				if(person==null){
					return AppUtil.returnMapJson("0", "查询失败!", null);
				}else{
					return AppUtil.returnMapJson("1", "查询成功!", null);
				}
			} catch (Exception e) {
				return AppUtil.returnMapJson("0", "查询失败!", null);
			}
	    }
	    /**
	     * @author 王永宁
	     * @说明 APP获取验证码
	     * @return
	     */
	    @RequestMapping("getVerificationCode")
	    @ResponseBody
	    public Object getVerificationCode(String phoneNumber) {
	        Map<String, Object> flag = new HashMap<>();
	        flag.put("flag","9");
	        // 传入参数电话号码不可空
	        if (phoneNumber != null && !"".equals(phoneNumber)) {
	            HashMap<String, Object> result = null;
	            CCPRestSDK restAPI = new CCPRestSDK();
	            restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
	            restAPI.setAccount("8a48b55150ac70fd0150acc34f1f01e4", "22ed8d4fa75e45978d35bc245326886d");// 初始化主帐号和主帐号TOKEN
	            restAPI.setAppId("8aaf07085995ddef01599b9407660171");// 初始化应用ID
	            
	            int num = (int) ((Math.random() * 9 + 1) * 100000);
	            // 这里生成验证码与验证码时限时间并存储表
	            
	            // sendTemplateSMS
	            // 参数1:必选参数 短信接收端手机号码集合，用英文逗号分开，每批发送的手机号数量不得超过100个
	            // 参数2:必选参数 模板Id
	            // 参数3:可选参数 内容数据，用于替换模板中{序号}
	            result = restAPI.sendTemplateSMS(phoneNumber, "153391", new String[]{num + "", "1"});
	            if ("000000".equals(result.get("statusCode"))) {
	                // 正常返回输出data包体信息（map）
	                HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
	                Set<String> keySet = data.keySet();
	                for (String key : keySet) {
	                    Object object = data.get(key);
	                }
	                flag.put("flag",num + "");
	                return AppUtil.returnMapJson("1", "获取验证码成功!", flag);
	            } else {
	                // 异常返回输出错误码和错误信息
	                flag.put("flag","9");
	                return AppUtil.returnMapJson("0", "获取验证码失败!错误信息:" + result.get("statusMsg"), flag);
	            }
	        } else {
	            flag.put("flag","9");
	            return AppUtil.returnMapJson("0", "手机号不能为空!", flag);
	        }
	    }
	    
	    /**
	     * @author 王永宁
	     * @说明 APP保存手机号
	     * @return
	     */
	    @RequestMapping("savePhoneNumber")
	    @ResponseBody
	    public Object savephone(String phoneNumber,String id,HttpServletRequest request) {
	    	try {
	    		TPersonnel person=new TPersonnel();
	    		person.setId(Integer.valueOf(id));
	    		person.setPhone(phoneNumber);
	    		personService.update(person);
	    		
	    		return AppUtil.returnMapJson("1", "更改手机号成功", null);
	    	} catch (Exception e) {
	    		return AppUtil.returnMapJson("0", "更改手机号失败", null);
	    	}
	    }
}
